<template>
  <!-- 顶部操作栏和显示用户名 -->
  <main
    data-tauri-drag-region
    class="relative z-30 flex-y-center border-b-(1px solid [--right-chat-footer-line-color]) select-none cursor-default justify-between p-[6px_22px_10px]">
    <n-flex align="center">
      <n-flex align="center">
        <n-avatar class="rounded-8px select-none" :size="28" :src="avatar || '/logo.png'" fallback-src="/logo.png" />
        <label class="flex-y-center gap-6px">
          <span class="text-(16px [--text-color])">{{ convName }}</span>
          <span class="text-(11px #808080)" v-if="isGROUP">(在线人数 {{ tencentGroupStore.groupOnlineMemberCount }} )</span>
        </label>
        <n-flex align="center">
          <template>
            <n-flex align="center" :size="6">
              <!-- 状态图标 -->
              <!--                <n-badge :color="isOnline ? '#1ab292' : '#909090'" dot />-->

              <!-- 状态文本 -->
              <p class="text-(12px [--text-color])">在线</p>
            </n-flex>
          </template>
        </n-flex>
      </n-flex>
    </n-flex>
    <!-- 顶部右边选项栏 -->
    <nav class="options flex-y-center gap-20px color-[--icon-color]">
      <!--      <div class="options-box">-->
      <!--        <n-popover trigger="hover" :show-arrow="false" placement="bottom">-->
      <!--          <template #trigger>-->
      <!--            <svg @click="void 0"><use href="#phone-telephone"></use></svg>-->
      <!--          </template>-->
      <!--          <span>话音通话</span>-->
      <!--        </n-popover>-->
      <!--      </div>-->

      <!--      <div class="options-box">-->
      <!--        <n-popover trigger="hover" :show-arrow="false" placement="bottom">-->
      <!--          <template #trigger>-->
      <!--            <svg><use href="#video-one"></use></svg>-->
      <!--          </template>-->
      <!--          <span>视频通话</span>-->
      <!--        </n-popover>-->
      <!--      </div>-->

      <!--      <div class="options-box">-->
      <!--        <n-popover trigger="hover" :show-arrow="false" placement="bottom">-->
      <!--          <template #trigger>-->
      <!--            <svg @click="void 0"><use href="#screen-sharing"></use></svg>-->
      <!--          </template>-->
      <!--          <span>屏幕共享</span>-->
      <!--        </n-popover>-->
      <!--      </div>-->

      <!--      <div class="options-box">-->
      <!--        <n-popover trigger="hover" :show-arrow="false" placement="bottom">-->
      <!--          <template #trigger>-->
      <!--            <svg><use href="#remote-control"></use></svg>-->
      <!--          </template>-->
      <!--          <span>远程协助</span>-->
      <!--        </n-popover>-->
      <!--      </div>-->

      <!--      <div class="options-box" @click="void 0">-->
      <!--        <n-popover trigger="hover" :show-arrow="false" placement="bottom">-->
      <!--          <template #trigger>-->
      <!--            <svg><use href="#launch"></use></svg>-->
      <!--          </template>-->
      <!--          <span>邀请进群</span>-->
      <!--          <span>发起群聊</span>-->
      <!--        </n-popover>-->
      <!--      </div>-->

      <div class="options-box" @click="sidebarShow = !sidebarShow">
        <svg><use href="#more"></use></svg>
      </div>
    </nav>

    <!-- 侧边选项栏 -->
    <Transition name="sidebar" v-if="isGROUP || isC2C">
      <div v-if="sidebarShow" style="border: 1px solid rgba(90, 90, 90, 0.1)" class="sidebar">
        <n-scrollbar style="height: calc(100vh - 50px)" class="p-22px box-border">
          <!-- 单聊侧边栏选项 -->
          <template v-if="isC2C">
            <div class="box-item flex-col-y-center">
              <div class="flex-between-center">
                <p>设为置顶</p>
                <n-switch size="small" :value="activeItem?.isPinned" @update:value="handleIsPinned" />
              </div>
              <div class="h-1px bg-[--setting-item-line] m-[10px_0]"></div>
              <div class="flex-between-center">
                <p>消息免打扰</p>
                <n-switch size="small" value="提示" />
              </div>
            </div>

            <!--            <div class="box-item">-->
            <!--              <div class="flex-between-center">-->
            <!--                <p>屏蔽此人</p>-->
            <!--                <n-switch size="small" :value="activeItem?.isPinned" />-->
            <!--              </div>-->
            <!--            </div>-->

            <div class="box-item flex-x-center cursor-pointer" @click="handleDelete('message')">
              <p>删除聊天记录</p>
            </div>

<!--            <p class="m-[0_auto] text-(12px #13987f center) mt-20px cursor-pointer">被骚扰了?&nbsp;&nbsp;举报该用户</p>-->
          </template>

          <!-- 群聊侧边栏选项 -->
          <template v-else>
            <div class="box-item cursor-default">
              <n-flex align="center" :size="10">
                <!-- 群头像 -->
                <div class="relative group">
                  <!-- 群主可以编辑头像，显示黑色蒙层和上传图标 -->
                  <div v-if="isOwner" class="avatar-wrapper relative" @click="void 0">
                    <n-avatar round :size="40" :src="avatar || '/logo.png'" />
                    <div class="avatar-hover absolute size-full rounded-50% flex-center">
                      <svg class="size-14px color-#fefefe"><use href="#Export"></use></svg>
                    </div>
                  </div>

                  <n-avatar v-else round :size="40" :src="avatar || '/logo.png'" />
                </div>

                <n-flex vertical :size="6">
                  <!-- 群名称 -->
                  <n-flex :size="10" align="center">
                    <div v-if="isOwner" class="flex-1">
                      <n-input
                        ref="groupNameInputRef"
                        v-model:value="groupProfile.name"
                        @blur="saveGroupName"
                        @keydown.enter="saveGroupName"
                        size="tiny"
                        maxlength="15"
                        autoComplete="off"
                        autoCorrect="off"
                        class="border-(solid 1px [--line-color])"
                        placeholder="请输入群名称(最多15字)" />
                    </div>
                    <div v-else class="text-(14px --text-color) cursor-default" :class="{ 'cursor-pointer': isOwner }">
                      {{ activeItem?.groupProfile.name }}
                      <!-- 显示编辑图标 -->
                      <svg v-if="isOwner" class="size-14px ml-1 inline-block color-[--icon-color]">
                        <use href="#edit"></use>
                      </svg>
                    </div>
                  </n-flex>

                  <n-flex align="center" :size="8">
                    <!-- hula号 -->
                    <p
                      class="text-(12px center [--chat-text-color]) rounded-4px w-100px py-2px bg-[#e3e3e3] dark:bg-[#505050]">
                      {{ activeItem?.groupProfile.groupID }}
                    </p>

                    <n-tooltip trigger="hover">
                      <template #trigger>
                        <svg
                          class="size-12px cursor-pointer hover:color-#909090 hover:transition-colors"
                          @click="handleCopy">
                          <use href="#copy"></use>
                        </svg>
                      </template>
                      <span>复制</span>
                    </n-tooltip>
                  </n-flex>
                </n-flex>
              </n-flex>
            </div>

            <!-- 群聊成员列表 -->
            <div class="box-item cursor-default">
              <n-flex vertical justify="center" :size="16">
                <p class="text-(14px --text-color)">群成员</p>

                <n-flex align="center" justify="start" :size="[24, 20]">
                  <template v-for="item in groupMemberList">
                    <n-flex vertical justify="center" align="center" :size="10">
                      <n-avatar round :size="30" :src="item.avatar || '/logo.png'" fallback-src="/logo.png" />

                      <p class="text-(10px --text-color center) w-30px truncate">{{ item.nameCard || item.nick }}</p>
                    </n-flex>
                  </template>
                </n-flex>
              </n-flex>
            </div>

            <!-- 我本群的昵称 -->
            <p class="text-(12px [--chat-text-color]) mt-20px mb-10px">我本群的昵称</p>
            <n-input
              class="border-(solid 1px [--line-color]) custom-shadow"
              autoComplete="off"
              autoCorrect="off"
              v-model:value="groupProfile.selfInfo.nameCard"
              @update:value="setGroupMemberNameCard" />

            <!-- 群设置选项 -->
            <div class="box-item cursor-default">
              <n-flex vertical justify="center" :size="4">
                <p class="text-(12px #909090) pb-14px">群设置</p>

                <div
                  class="flex-between-center cursor-pointer"
                  @click="notificationInfoShow = !notificationInfoShow"
                  title="群公告">
                  <p class="">群公告</p>
                </div>

                <div class="h-1px bg-[--setting-item-line] m-[10px_0]"></div>

                <div class="flex-between-center">
                  <p>设为置顶</p>
                  <n-switch size="small" :value="activeItem?.isPinned" @update:value="handleIsPinned" />
                </div>

                <div class="h-1px bg-[--setting-item-line] m-[10px_0]"></div>

                <div class="flex-between-center">
                  <p>消息免打扰</p>
                  <n-switch size="small" value="提示" />
                </div>

                <template v-if="isOwner">
                  <div class="h-1px bg-[--setting-item-line] m-[10px_0]"></div>

                  <div class="flex-between-center">
                    <p>全体禁言</p>
                    <n-switch size="small" value="提示" />
                  </div>

                  <div class="h-1px bg-[--setting-item-line] m-[10px_0]"></div>

                  <div class="">
                    <n-flex vertical justify="center">
                      <p class="pb-14px">入群方式</p>

                      <div class="flex-between-center">
                        <n-select
                          v-model:value="groupProfile.joinOption"
                          :options="joinOptions"
                          @update:value="handleJoinOption" />
                      </div>
                    </n-flex>
                  </div>
                </template>
              </n-flex>
            </div>

            <div class="box-item flex-x-center cursor-pointer mb-20px" @click="handleDelete('message')">
              <p>删除聊天记录</p>
            </div>

            <div
              class="box-item flex-x-center cursor-pointer mb-20px"
              @click="handleDelete(isOwner ? 'dismissGroup' : 'quitGroup')">
              <p class="color-#d03553">{{ isOwner ? '解散群聊' : '退出群聊' }}</p>
            </div>

<!--            <p class="text-(12px #13987f center) my-20px cursor-pointer">被骚扰了?&nbsp;&nbsp;举报该群</p>-->
          </template>
        </n-scrollbar>
      </div>
    </Transition>
  </main>

  <n-modal
    v-model:show="notificationInfoShow"
    :mask-closable="false"
    transform-origin="center"
    :on-mask-click="handleMaskClick">
    <div class="bg-[--bg-edit] w-480px h-fit box-border flex flex-col">
      <n-flex vertical class="size-full flex-center">
        <div class="text-(14px [--chat-text-color]) flex-start-center w-95% h-40px">公告</div>
        <div class="w-95%">
          <n-input
            class="max-h-480px border-(1px solid #90909080) rounded-6px bg-[--center-bg-color]"
            v-model:value="groupProfile.notification"
            type="textarea"
            placeholder="填写公告，1～200字"
            :autosize="{ minRows: 20 }"
            maxlength="200"
            autoComplete="off"
            autoCorrect="off"
            :readonly="!isOwner && !isAdmin"
            show-count
            autofocus />
        </div>
        <n-flex justify="space-between" class="w-95%">
          <div class="w-40% h-42px flex-start-center"></div>
          <div class="w-45% h-42px flex-end-center">
            <n-button quaternary size="small" class="bg-[--button-bg]" @click="notificationInfoShow = false"
              >取消</n-button
            >
            <n-button
              v-if="isOwner || isAdmin"
              secondary
              type="primary"
              size="small"
              class="bg-[--button-bg] ml-5px"
              @click="handleSaveNotification">
              保存
            </n-button>
          </div>
        </n-flex>
      </n-flex>
    </div>
  </n-modal>

  <!-- 弹出框 -->
  <n-modal v-model:show="modalShow" class="w-350px rounded-8px">
    <div class="bg-[--bg-popover] w-360px h-full p-6px box-border flex flex-col">
      <div
        v-if="type() === 'macos'"
        @click="modalShow = false"
        class="mac-close z-999 size-13px shadow-inner bg-#ed6a5eff rounded-50% select-none absolute left-6px">
        <svg class="hidden size-7px color-#000 font-bold select-none absolute top-3px left-3px">
          <use href="#close"></use>
        </svg>
      </div>

      <svg v-if="type() === 'windows'" @click="modalShow = false" class="size-12px ml-a cursor-pointer select-none">
        <use href="#close"></use>
      </svg>
      <div class="flex flex-col gap-30px p-[22px_10px_10px_22px] select-none">
        <span class="text-14px">{{ tips }}</span>

        <n-flex justify="end">
          <n-button @click="handleConfirm" class="w-78px" color="#13987f">确定</n-button>
          <n-button @click="modalShow = false" class="w-78px" secondary>取消</n-button>
        </n-flex>
      </div>
    </div>
  </n-modal>

  <!-- 添加裁剪组件和文件输入框 -->
  <input
    ref="fileInput"
    type="file"
    accept="image/jpeg,image/png,image/webp"
    class="hidden"
    @change="handleFileChange" />
  <AvatarCropper ref="cropperRef" v-model:show="showCropper" :image-url="localImageUrl" @crop="handleCrop" />
</template>

<script setup lang="ts">
import { type } from '@tauri-apps/plugin-os'
import TencentCloudChat, { Conversation } from '@tencentcloud/chat'
import { useTencentConversationStore } from '@/stores/tencentConversationStore.ts'
import { useTencentGroupStore } from '@/stores/tencentGroupStore.ts'
import { useMitt } from '@/hooks/useMitt.ts'
import { useTencentMessageStore } from '@/stores/tencentMessageStore.ts'

const { activeItem } = defineProps<{
  activeItem?: Conversation
}>()
const tencentConversationStore = useTencentConversationStore()
const tencentGroupStore = useTencentGroupStore()
const tencentMessageStore = useTencentMessageStore()
const TYPES = TencentCloudChat.TYPES
const sidebarShow = ref(false)
const modalShow = ref(false)
const showCropper = ref(false)
const localImageUrl = ref('')
const notificationInfoShow = ref(false)
const handleCrop = () => {}
const handleFileChange = () => {}
const tips = ref('提示')
const optionType = ref<string>('')
const joinOptions = ref([
  { label: '自由加入', value: TencentCloudChat.TYPES.JOIN_OPTIONS_FREE_ACCESS },
  { label: '需要验证', value: TencentCloudChat.TYPES.JOIN_OPTIONS_NEED_PERMISSION },
  { label: '禁止加入', value: TencentCloudChat.TYPES.JOIN_OPTIONS_DISABLE_APPLY }
])

const isGROUP = computed(() => activeItem?.type === TYPES.CONV_GROUP)
const isC2C = computed(() => activeItem?.type === TYPES.CONV_C2C)
const isOwner = computed(() => isGROUP && activeItem?.groupProfile.ownerID === activeItem?.groupProfile.selfInfo.userID)
const isAdmin = computed(() => activeItem?.groupProfile.selfInfo.role === TencentCloudChat.TYPES.GRP_MBR_ROLE_ADMIN)
const groupProfile = computed(() => tencentGroupStore.currentGroup)
const groupMemberList = computed(() => tencentGroupStore.groupMemberMap[groupProfile.value.groupID!])
const avatar = computed(() => {
  if (activeItem?.type === TYPES.CONV_GROUP) {
    return activeItem?.groupProfile.avatar
  } else if (activeItem?.type === TYPES.CONV_C2C) {
    return activeItem?.userProfile.avatar
  }

  return ''
})

const convName = computed(() => {
  if (activeItem?.type === TYPES.CONV_GROUP) {
    return activeItem?.groupProfile.name
  } else if (activeItem?.type === TYPES.CONV_C2C) {
    return activeItem?.remark || activeItem?.userProfile.nick || activeItem?.userProfile.userID
  }

  return '系统消息'
})

const handleIsPinned = (value: boolean) => {
  if (activeItem?.hasOwnProperty('isPinned')) {
    activeItem['isPinned'] = value
  }
  tencentConversationStore.pinConversation({ conversationID: activeItem?.conversationID as string, isPinned: value })
}

const handleJoinOption = () => {
  tencentGroupStore.updateGroupProfile({
    groupID: groupProfile.value.groupID,
    joinOption: groupProfile.value.joinOption
  })
}

// 验证公告内容
const validateNotification = (content: string) => {
  console.log(content.length, content)
  if (content.length < 1) {
    window.$message.error('公告内容不能为空')
    return false
  }
  if (content.length > 600) {
    window.$message.error('公告内容不能超过600字')
    return false
  }
  return true
}

const handleSaveNotification = () => {
  if (!validateNotification(groupProfile?.value?.notification as string)) {
    return
  }

  tencentGroupStore.updateGroupProfile({
    groupID: groupProfile.value.groupID,
    notification: groupProfile.value.notification
  })
}

const handleMaskClick = () => {
  notificationInfoShow.value = false
}

const saveGroupName = () => {
  const groupName = groupProfile.value?.name || ''
  if (groupName.length < 1) {
    window.$message.error('群名称不能为空')
    return false
  }

  if (groupName.length > 15) {
    window.$message.error('群名称长度超过15个字符')
    return false
  }

  tencentGroupStore.updateGroupProfile({
    groupID: groupProfile.value.groupID,
    name: groupName
  })
}

const setGroupMemberNameCard = () => {
  tencentGroupStore.setGroupMemberNameCard({
    groupID: groupProfile.value.groupID,
    userID: groupProfile.value.selfInfo.userID,
    nameCard: groupProfile.value.selfInfo.nameCard
  })
}

const handleDelete = (label: string) => {
  modalShow.value = true
  optionType.value = label

  if (label === 'message') {
    tips.value = '删除后无法恢复，确定删除聊天记录吗？'
  } else if (label === 'dismissGroup') {
    tips.value = '确定要解散群聊吗？'
  } else if (label === 'quitGroup') {
    tips.value = '确定要退出群聊吗？'
  }
}

const handleConfirm = () => {
  if (optionType.value === 'message') {
    tencentMessageStore.clearHistoryMessage(activeItem?.conversationID as string)
  } else if (optionType.value === 'dismissGroup') {
    if (groupProfile.value.groupID) {
      tencentGroupStore.dismissGroup(groupProfile.value?.groupID)
    }
  } else if (optionType.value === 'quitGroup') {
    if (groupProfile.value.groupID) {
      tencentGroupStore.quitGroup(groupProfile.value.groupID)
    }
  }
}

const closeMenu = (event: any) => {
  /** 点击非侧边栏元素时，关闭侧边栏，但点击弹出框元素、侧边栏图标、还有侧边栏里面的元素时不关闭 */
  if (!event.target.matches('.sidebar, .sidebar *, .n-modal-mask, .options-box *, .n-modal *') && !modalShow.value) {
    if (sidebarShow.value) {
      // 如果侧边栏正在显示，则在关闭前保存信息
    }
    sidebarShow.value = false
  }
}

// 处理复制账号
const handleCopy = () => {
  navigator.clipboard.writeText(activeItem?.groupProfile.groupID as string)
  window.$message.success(`复制成功 ${activeItem?.groupProfile.groupID}`)
}

watch(
  () => activeItem,
  (newVal, oldVal) => {
    if (newVal?.conversationID !== oldVal?.conversationID && newVal?.type === TencentCloudChat.TYPES.CONV_GROUP) {
      tencentGroupStore.getGroupOnlineMemberCount(newVal?.groupProfile?.groupID!)
    }
  }
)

onMounted(() => {
  window.addEventListener('click', closeMenu, true)
  useMitt.on('groupNotification', () => {
    notificationInfoShow.value = false
  })

  // 如果是群聊，初始化时获取群组详情
  if (isGROUP) {
  }
})

onUnmounted(() => {
  window.removeEventListener('click', closeMenu, true)
})
</script>

<style scoped lang="scss">
@use '@/styles/scss/chat-header';

.loading-enter-active,
.loading-leave-active {
  transition: opacity 0.3s ease;
}

.loading-enter-from,
.loading-leave-to {
  opacity: 0;
}

.avatar-wrapper {
  cursor: pointer;

  .avatar-hover {
    opacity: 0;
    transition: opacity 0.4s ease-in-out;
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
    top: 0;
    left: 0;
  }

  &:hover .avatar-hover {
    opacity: 1;
  }
}

:deep(.n-scrollbar > .n-scrollbar-container > .n-scrollbar-content) {
  padding-left: 2px;
}
</style>
